import 'dart:convert';

import 'package:get/get.dart';
import 'package:projectfluttershengyihuatong/category/CatetoryModel.dart';
import 'package:projectfluttershengyihuatong/service/jsontool.dart';
import 'package:projectfluttershengyihuatong/service/loginService/logginservice.dart';
import 'package:projectfluttershengyihuatong/service/request_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CatetoryController extends GetxController {
  /// 单例对象
  static CatetoryController? _instance;

  /// 内部构造方法，可避免外部暴露构造函数，进行实例化
  CatetoryController._internal();

  /// 工厂构造方法，这里使用命名构造函数方式进行声明
  factory CatetoryController.getInstance() => _getInstance();

  /// 获取单例内部方法
  static _getInstance() {
    // 只能有一个实例
    _instance ??= CatetoryController._internal();
    return _instance;
  }

  List<CatetoryModel> dataArr = [];

  static request() async {
    var shareManager = await SharedPreferences.getInstance();
    // var olddata = shareManager.getString(CatetoryController.catetory);
    // if (olddata != null && olddata!.isNotEmpty) {
    //   var json = jsonDecode(olddata!);
    //   var model = BaseModel<List<CatetoryModel>>.fromJson(json);
    //   CatetoryController.getInstance().dataArr = model.data ?? [];
    //   CatetoryController.getInstance().update([CatetoryController.categoryList]);
    // }

    if (LoginService.getInstance().userInfo?.token != null) {
      RequestManager.getInstance().dio.options.headers["token"] =
          LoginService.getInstance().userInfo?.token ?? "";
    }

    var response = await RequestManager.getInstance()
        .dio
        .get('/api/stuProject/menLeiList');
    var result = response.data;
    final jsonStr = jsonEncode(result);
    await shareManager.setString(CatetoryController.category, jsonStr);
    final model = BaseModel<List<CatetoryModel>>.fromJson(result);

    //获取上次点击的门类信息

    await CatetoryController.getInstance().getSaveCatetory();
    if (CatetoryController.getInstance().leiModel != null && CatetoryController.getInstance().menModel != null) {
      //找到对应的门类。设置选择。
      model.data?.forEach((element) {
        if (element.pid == CatetoryController.getInstance().menModel?.pid) {
          element.isSelected = true;
          CatetoryController.getInstance().menModel = element;
          element.children?.forEach((leiElement) {
            if (leiElement.pid == CatetoryController.getInstance().leiModel?.pid) {
              leiElement.isSelected = true;
            }
          });
          CatetoryController.getInstance().leiModel = element;
        }
      });
    } else {
      model.data?.first.isSelected = true;
      model.data?.first.children?.first.isSelected = true;
      CatetoryController.getInstance().menModel = model.data?.first;
      CatetoryController.getInstance().leiModel = model.data?.first?.children?.first;
    }

    CatetoryController.getInstance().dataArr = model.data ?? [];
    CatetoryController.getInstance().update([CatetoryController.categoryList]);
  }

  static const category = "catetory";
  static const categoryList = "categoryList";
  static const leiCategory = "leiCategory";
  static const menM = "menModel";
  static const leiM = "leiModel";

  CatetoryModel? leiModel;
  CatetoryModel? menModel;

  Future<void> saveLeiModel() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    if (leiModel != null && menModel != null) {
      final value = jsonEncode(leiModel);
      final menValue = jsonEncode(menModel);
      sharedPreferences.setString(CatetoryController.leiM, value);
      sharedPreferences.setString(CatetoryController.menM, menValue);
    }
  }


  Future<void> getSaveCatetory() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    var leiData = sharedPreferences.getString(CatetoryController.leiM);
    var menModel = sharedPreferences.getString(CatetoryController.menM);

    if (leiData != null && menModel != null) {
      try {
        var json = jsonDecode(leiData);
        this.leiModel = CatetoryModel.fromJson(json);

        final menJson = jsonDecode(menModel);
        this.menModel = CatetoryModel.fromJson(menJson) ;


        update([CatetoryController.leiCategory]);
      } catch (error) {
        print(error);
      }
    } else {}
  }
}
